package com.hq.talk.view.base;

import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hq.lib_comview.common.code.CodeStatus;
import com.hq.lib_comview.common.utils.StringUtils;
import com.hq.lib_comview.view.observable.ObservableListView;
import com.hq.lib_comview.view.observable.ObservableRecyclerView;
import com.hq.lib_comview.view.observable.ObservableScrollViewCallbacks;
import com.hq.lib_comview.view.observable.ScrollState;
import com.hq.lib_comview.view.scprogress.SVProgressHUD;
import com.hq.lib_comview.view.selview.MyGifView;
import com.hq.talk.R;
import com.hq.talk.presenter.IViewController;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 功能：公用的带下拉刷新和没网络时数据显示的效果
 * 说明：处理列表
 */
public class BaseCommAty extends CheckPermissionsAty implements ObservableScrollViewCallbacks {

    /**
     * 网络或者数据加载错误，弹出框提示
     */
    @BindView(R.id.id_refresh_status_ll)
    RelativeLayout mRefreshErrorLL;
    @BindView(R.id.id_refresh_status_txt)
    TextView mTxtRefreshError;

    /**
     * 网络或者数据加载错误，背景界面
     */
    @BindView(R.id.id_comm_fail_ll)
    View mErrorNetOrData;
    //显示图片
    @BindView(R.id.id_comm_fail_img)
    ImageView mImgError;
    //显示文字
    @BindView(R.id.id_comm_fail_txt)
    TextView mTxtError;

    /**
     * Gif图
     */
    @BindView(R.id.id_show_gif)
    RelativeLayout mShowGifView;
    @BindView(R.id.id_gif_view)
    MyGifView myGifView;

    /**
     * 内容区域
     */
    public FrameLayout mCommContentLl;

    @Nullable
    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        View view = inflater.inflate(R.layout.layout_comm_refresh_data, null, false);
        mCommContentLl = (FrameLayout) view.findViewById(R.id.id_comm_content_ll);
        if (null != childView) {
            if (null != mCommContentLl) {
                mCommContentLl.addView(childView);
            }
        }
        return view;
    }

    /**
     * 处理非列表界面数据加载，返回状态码，弹出提示框
     *
     * @param mView
     * @param isHandler
     * @param loadingStatus
     * @param string
     */
    @Override
    public void onLoadingStatus(IViewController mView, boolean isHandler, int loadingStatus, int flag, String string) {
        if (null == aty) {
            return;
        }
        dataStatus(4);
        switch (loadingStatus) {
            //网络错误
            case CodeStatus.Gegeneral.ERROR_NET:
                if (null != aty)
                    SVProgressHUDDismiss();
                if (hasDataInPage()) {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, false, string);
                    } else {
                        //弹出提示框
                        if (!StringUtils.isEmpty(string) && null != aty && !isFinishing()) {
                            SVProgressHUD.showErrorWithStatus(aty, string);
                        } else {
                            //界面有数据，提示网络出错
                            showRemindDialog(0, 0);
                        }
                    }
                } else {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, false, string);
                    } else {
                        dataStatus(1);
                    }
                }
                break;
            //数据加载中
            case CodeStatus.Gegeneral.DATA_LOADING:
                if (null != aty)
                    SVProgressHUDDismiss();
                if (hasDataInPage()) {
                    if (isHandler && null != mView) {
                        //自己处理状态
                        mView.handlerByPage(loadingStatus, flag, false, string);
                    } else {
                        //弹出提示框
                        if (!StringUtils.isEmpty(string) && null != aty && !isFinishing()) {
                            SVProgressHUD.showWithStatus(aty, string);
                        } else {
//                            dataStatus(5);
                        }
                    }
                } else {
                    if (isHandler && null != mView) {
                        //自己处理状态
                        mView.handlerByPage(loadingStatus, flag, false, string);
                    } else {
                        dataStatus(0);
                    }
                }
                break;
            //数据加载失败
            case CodeStatus.Gegeneral.ERROR_DATA:
                if (null != aty)
                    SVProgressHUDDismiss();
                if (hasDataInPage()) {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, false, string);
                    } else {
                        //弹出提示框
                        if (!StringUtils.isEmpty(string) && null != aty && !isFinishing()) {
                            SVProgressHUD.showErrorWithStatus(aty, string);
                        } else {
                            //界面有数据，提示数据加载失败
                            showRemindDialog(1, 0);
                        }
                    }
                } else {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, false, string);
                    } else {
                        dataStatus(2);
                    }
                }
                break;
            //数据获取成功，列表有数据
            case CodeStatus.Gegeneral.DATA_SUCCESS_FULL:
                if (null != aty)
                    SVProgressHUDDismiss();
                if (hasDataInPage()) {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, false, string);
                    } else {
                        //弹出提示框
                        if (!StringUtils.isEmpty(string) && null != aty && !isFinishing()) {
                            SVProgressHUD.showSuccessWithStatus(aty, string);
                        }
                    }
                } else {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, false, string);
                    } else {
                        //弹出提示框
                        if (!StringUtils.isEmpty(string) && !SVProgressHUD.isShowing(aty)) {
                            SVProgressHUD.showSuccessWithStatus(aty, string);
                        }
                    }
                }
                break;
            //数据获取成功，列表没有数据
            case CodeStatus.Gegeneral.DATA_SUCCESS_NULL:
                if (null != aty)
                    SVProgressHUDDismiss();
                if (hasDataInPage()) {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, false, string);
                    } else {
                        //弹出提示框
                        if (!StringUtils.isEmpty(string) && null != aty && !isFinishing()) {
                            SVProgressHUD.showInfoWithStatus(aty, string);
                        } else {
                            showRemindDialog(2, 0);
                        }
                    }
                } else {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, false, string);
                    } else {
                        //显示暂无数据
                        dataStatus(3);
                    }
                }
                break;
        }
    }

    @Override
    public void onLoadingStatus(IViewController mView, boolean isHandler, int loadingStatus, int flag, String string, boolean loadMore) {
        if (null == aty) {
            return;
        }
        dataStatus(4);
        switch (loadingStatus) {
            //网络错误
            case CodeStatus.Gegeneral.ERROR_NET:
                if (hasDataInPage()) {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, loadMore, string);
                    } else {
                        //界面有数据，提示网络出错
                        showRemindDialog(0, 0);
                    }
                } else {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, loadMore, string);
                    } else {
                        dataStatus(1);
                    }
                }
                break;
            //数据加载中
            case CodeStatus.Gegeneral.DATA_LOADING:
                if (hasDataInPage()) {
                    if (isHandler && null != mView) {
                        //自己处理状态
                        mView.handlerByPage(loadingStatus, flag, loadMore, string);
                    }
                } else {
                    if (isHandler && null != mView) {
                        //自己处理状态
                        mView.handlerByPage(loadingStatus, flag, loadMore, string);
                    } else {
                        dataStatus(0);
                    }
                }
                break;
            //数据加载失败
            case CodeStatus.Gegeneral.ERROR_DATA:
                if (hasDataInPage()) {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, loadMore, string);
                    } else {
                        //界面有数据，提示数据加载失败
                        showRemindDialog(1, 0);
                    }
                } else {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, loadMore, string);
                    } else {
                        dataStatus(2);
                    }
                }
                break;
            //数据获取成功，列表有数据
            case CodeStatus.Gegeneral.DATA_SUCCESS_FULL:
                if (hasDataInPage()) {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, loadMore, string);
                    }
                } else {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, loadMore, string);
                    }
                }
                break;
            //数据获取成功，列表没有数据
            case CodeStatus.Gegeneral.DATA_SUCCESS_NULL:
                if (hasDataInPage()) {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, loadMore, string);
                    } else {
                        showRemindDialog(2, 0);
                    }
                } else {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, loadMore, string);
                    } else {
                        //显示暂无数据
                        dataStatus(3);
                    }
                }
                break;
        }
    }

    @Override
    public void onLoadingStatus(IViewController mView, boolean isHandler, int loadingStatus, int flag, String string, boolean loadMore, int size) {
        if (null == aty) {
            return;
        }
        dataStatus(4);
        switch (loadingStatus) {
            //网络错误
            case CodeStatus.Gegeneral.ERROR_NET:
                if (hasDataInPage()) {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, loadMore, size, string);
                    } else {
                        //界面有数据，提示网络出错
                        showRemindDialog(0, 0);
                    }
                } else {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, loadMore, size, string);
                    } else {
                        //界面没有数据，显示没有网络界面，点击界面可以直接调用刷新接口
                        dataStatus(1);
                    }
                }
                break;
            //数据加载中
            case CodeStatus.Gegeneral.DATA_LOADING:
                if (hasDataInPage()) {
                    if (isHandler && null != mView) {
                        //自己处理状态
                        mView.handlerByPage(loadingStatus, flag, loadMore, size, string);
                    }
                } else {
                    if (isHandler && null != mView) {
                        //自己处理状态
                        mView.handlerByPage(loadingStatus, flag, loadMore, size, string);
                    } else {
                        //界面显示数据正在加载
                        dataStatus(0);
                    }
                }
                break;
            //数据加载失败
            case CodeStatus.Gegeneral.ERROR_DATA:
                if (hasDataInPage()) {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, loadMore, size, string);
                    } else {
                        //界面有数据，提示数据加载失败
                        showRemindDialog(1, 0);
                    }
                } else {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, loadMore, size, string);
                    } else {
                        dataStatus(2);
                    }
                }
                break;
            //数据获取成功，列表有数据
            case CodeStatus.Gegeneral.DATA_SUCCESS_FULL:
                if (hasDataInPage()) {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, loadMore, size, string);
                    } else {
                        showRemindDialog(2, size);
                    }
                } else {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, loadMore, size, string);
                    } else {
                        showRemindDialog(2, size);
                    }
                }
                break;
            //数据获取成功，列表没有数据
            case CodeStatus.Gegeneral.DATA_SUCCESS_NULL:
                if (hasDataInPage()) {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, loadMore, size, string);
                    } else {
                        showRemindDialog(0, 0);
                    }
                } else {
                    if (isHandler && null != mView) {
                        //自己处理
                        mView.handlerByPage(loadingStatus, flag, loadMore, size, string);
                    } else {
                        dataStatus(3);
                    }
                }
                break;
        }
    }

    /**
     * 界面数据状态,切换界面
     *
     * @param flag 0 表示正在加载，1 表示网络，2 表示数据错误,3表示暂无数据 4数据刷新成功 5表示界面有数据，显示正在加载图标
     */
    public void dataStatus(int flag) {
        if (null == mErrorNetOrData || null == mImgError || null == mTxtError || null == mCommContentLl || null == mShowGifView || null == myGifView || isFinishing()) {
            return;
        }
        mCommContentLl.setVisibility(View.GONE);
        mShowGifView.setVisibility(View.GONE);
        mErrorNetOrData.setVisibility(View.VISIBLE);
        if (flag == 0) {
            //正在加载
            mImgError.setBackgroundResource(R.drawable.ic_bg_loading);
            mTxtError.setText(getString(R.string.data_loading));
        } else if (flag == 1) {
            //网络出错
            mImgError.setImageResource(R.drawable.ic_bg_net_error);
            mTxtError.setText(getString(R.string.no_net_work));
        } else if (flag == 2) {
            //数据错误
            mImgError.setImageResource(R.drawable.ic_bg_loading);
            mTxtError.setText(getString(R.string.data_load_fail));
        } else if (flag == 3) {
            //暂无数据
            mImgError.setImageResource(R.drawable.ic_bg_loading);
            mTxtError.setText(getString(R.string.data_is_null));
        } else if (flag == 4) {
            // 数据刷新成功
            mErrorNetOrData.setVisibility(View.GONE);
            mCommContentLl.setVisibility(View.VISIBLE);
        } else if (flag == 5) {
            mCommContentLl.setVisibility(View.VISIBLE);
            mShowGifView.setVisibility(View.VISIBLE);
            mErrorNetOrData.setVisibility(View.GONE);
            // 设置背景gif图片资源
            myGifView.setMovieResource(R.raw.ic_lottery_loading);
        }
    }

    /**
     * 弹出提醒框
     *
     * @param flag 0 表示网络错误 1 表示数据加载错误 2 表示有新数据
     */
    public void showRemindDialog(int flag, int size) {
        if (null == mRefreshErrorLL || null == mTxtRefreshError || !isFinishing()) {
            return;
        }
        if (flag == 0) {
            mRefreshErrorLL.setBackgroundResource(R.color.color_ff6060);
            mTxtRefreshError.setText(getString(R.string.no_net_work));
        } else if (flag == 1) {
            mRefreshErrorLL.setBackgroundResource(R.color.color_ff6060);
            mTxtRefreshError.setText(getString(R.string.data_load_fail));
        } else if (flag == 2) {
            mRefreshErrorLL.setBackgroundResource(R.color.color_ffd102);
            if (size <= 0) {
                mTxtRefreshError.setText(getString(R.string.have_a_rest));
            } else {
                mTxtRefreshError.setText(size + getString(R.string.have_some_news));
            }
        }
        mRefreshErrorLL.setVisibility(View.VISIBLE);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefreshErrorLL.setVisibility(View.GONE);
            }
        }, 1000);
    }

    IRefreshPageListener mListener;

    public interface IRefreshPageListener {
        void refreshPage();
    }

    public void setOnRefreshDataListener(IRefreshPageListener mListener) {
        this.mListener = mListener;
    }

    /**
     * 刷新界面
     */
    @OnClick(R.id.id_comm_fail_ll)
    public void onClick(View mView) {
        if (mListener != null)
            mListener.refreshPage();
    }

    @Override
    public void requestPermissionResult(boolean allowPermission) {

    }

    //搜索框搜索
    private SearchBarClick mSearchBarClick;
    //记录第一个搜索框
    FrameLayout mSearchTop;
    //记录第二个搜索框
    private ViewGroup mSearchWrapper;
    private int searchHeight = 0;
    private Animation inAnim, outAnim;
    private boolean canAnim = false;

    public interface SearchBarClick {
        void onSearchBarClick();
    }

    private View.OnClickListener searchClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mSearchBarClick != null) {
                mSearchBarClick.onSearchBarClick();
            }
        }
    };

    /**
     * 添加搜索框
     *
     * @param observableListView
     * @param searchBarClick
     */
    protected void initSearchBar(ObservableListView observableListView, SearchBarClick searchBarClick, String desc) {
        this.mSearchBarClick = searchBarClick;
        mSearchTop = (FrameLayout) getLayoutInflater().inflate(R.layout.layout_comm_search_bar, mCommContentLl, false);
        ((TextView) mSearchTop.findViewById(R.id.id_search_key)).setText(desc);
        mSearchTop.setVisibility(View.VISIBLE);
        mSearchTop.setOnClickListener(searchClickListener);
        mCommContentLl.addView(mSearchTop);
        if (searchHeight == 0) {
            mSearchTop.measure(0, 0);
            searchHeight = (int) (mSearchTop.getMeasuredHeight());
        }
        mSearchWrapper = (ViewGroup) getLayoutInflater().inflate(R.layout.layout_comm_search_bar, null, false);
        ((TextView) mSearchWrapper.findViewById(R.id.id_search_key)).setText(desc);
        mSearchWrapper.setVisibility(View.VISIBLE);
        mSearchWrapper.setOnClickListener(searchClickListener);
        observableListView.addHeaderView(mSearchWrapper);
        observableListView.setScrollViewCallbacks(this);
        initAnim();
    }

    /**
     * 移除头部搜索框
     *
     * @param observableListView
     */
    protected void removeTopSearch(ObservableListView observableListView) {
//        observableListView.setOnScrollListener(null);
        if (mSearchTop != null) {
            mSearchTop.setVisibility(View.GONE);
            observableListView.removeHeaderView(mSearchWrapper);
        }
    }

    /**
     * 添加头部搜索框
     *
     * @param observableListView
     */
    protected void TopaddSearch(ObservableListView observableListView) {
//        observableListView.setOnScrollListener(null);
        if (mSearchTop != null) {
            mSearchTop.setVisibility(View.VISIBLE);
            observableListView.addHeaderView(mSearchWrapper);
        }
    }

    private void initAnim() {
        if (outAnim == null) {
            outAnim = AnimationUtils.loadAnimation(aty, R.anim.top_out_anim);
            outAnim.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    mSearchTop.setVisibility(View.INVISIBLE);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });

            inAnim = AnimationUtils.loadAnimation(aty, R.anim.top_in_anim);
            inAnim.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    mSearchTop.setVisibility(View.VISIBLE);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            });
        }
    }

    @Override
    public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
        canAnim = scrollY > searchHeight;
        if (scrollY == 0) {
            mSearchTop.setAlpha(0);
            mSearchTop.setClickable(false);
//            mSearchTop.requestDisallowInterceptTouchEvent(true);
        } else {
            if (mSearchTop.getAlpha() == 0) {
                mSearchTop.setAlpha(1);
//                mSearchTop.requestDisallowInterceptTouchEvent(false);
                mSearchTop.setClickable(true);
            }
        }
    }

    @Override
    public void onDownMotionEvent() {

    }

    @Override
    public void onUpOrCancelMotionEvent(ScrollState scrollState) {
        if (scrollState == ScrollState.UP) {
            if (mSearchTop.getVisibility() == View.VISIBLE && canAnim) {
                mSearchTop.startAnimation(outAnim);
            }
        } else if (scrollState == ScrollState.DOWN && canAnim) {
            if (mSearchTop.getVisibility() == View.INVISIBLE) {
                mSearchTop.startAnimation(inAnim);
            }
        }
    }

    protected void initSearchBar(ObservableRecyclerView observableRecyclerView, SearchBarClick searchBarClick, String desc) {
        this.mSearchBarClick = searchBarClick;
        mSearchTop = (FrameLayout) getLayoutInflater().inflate(R.layout.layout_comm_search_bar, mCommContentLl, false);
        ((TextView) mSearchTop.findViewById(R.id.id_search_key)).setText(desc);
        mCommContentLl.addView(mSearchTop);
        if (searchHeight == 0) {
            mSearchTop.measure(0, 0);
            Log.d("audio", "searchHeight " + mSearchTop.getMeasuredHeight());
            searchHeight = (int) (mSearchTop.getMeasuredHeight());
        }
        mSearchTop.setOnClickListener(searchClickListener);
        observableRecyclerView.setScrollViewCallbacks(this);
        initAnim();
    }

    /**
     * 子类添加头部搜索框
     *
     * @param parent
     * @param desc
     * @return
     */
    protected View getSearchLayout(ViewGroup parent, String desc) {
        mSearchWrapper = (ViewGroup) getLayoutInflater().inflate(R.layout.layout_comm_search_bar, parent, false);
        ((TextView) mSearchWrapper.findViewById(R.id.id_search_key)).setText(desc);
        mSearchWrapper.setVisibility(View.VISIBLE);
        mSearchWrapper.setOnClickListener(searchClickListener);
        return mSearchWrapper;
    }
}
